import React, { PureComponent } from 'react';
import _ from 'lodash';
import { Row, Col, message } from 'antd';
import { ContentPackage, FirstHeaderC, AdvancedSearch, DATA_ENTRY, PrimaryC, TableC, ModalC, FormGroup } from '../../../comps';
import config from '../../../comps/business/searchAndSelect/enum';
import moment from 'moment';
import UpdateModelC from './updateModelC';

import { connect, routerRedux } from 'dva';

@connect(({ qualificationManagementPlanMaintenanceM, loading, globalM }) => ({ qualificationManagementPlanMaintenanceM, loading, globalM }))
export default class QualificationManagementPlanMaintenance extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      id: '',
      searchObj: {},
      currentPage: 1,
      numInPage: 10,
      total: 0,
      columns: [
        { dataIndex: 'tradingcode', title: '证券代码', key: 'tradingcode' },
        { dataIndex: 'secuabbr', title: '证券简称', key: 'secuabbr' },
        { dataIndex: 'manager', title: '管理人', key: 'manager' },
        { dataIndex: 'planCreateDate', title: '成立日', key: 'planCreateDate' },
        { dataIndex: 'planEndDate', title: '到期日', key: 'planEndDate' },
        { dataIndex: 'assetType', title: '资产类别', key: 'assetType' },
        { dataIndex: 'rateType', title: '利率类型', key: 'rateType' },
      ],
      dataSource: undefined,
      isReset: false, // 是否点击重置
      operatePageVisible: false, // 新增或编辑页的显示隐藏
      operateType: 1, //操作类型,  operateType=1 新增, operateType=2 编辑 operateType=3 详情  operateType=4 估值解析
      isReportPermissionBefore: false,
      deferDateVisible: false, //展期模态框的显示隐藏
      deferDateData: undefined, //展期的数据回填
      sortedInfo: null, //排序对象
    };
  }
  componentDidMount() {
    const {
      globalM: { dataDictionary = {} },
    } = this.props;
    this.props.dispatch({
      type: 'qualificationManagementPlanMaintenanceM/getDictionList',
      // [管理方式  ，  资产类别 资金实际投向,资产管理计划属性,购买结构,计息基础,利率类型]
      payload: {
        dictData: dataDictionary,
      },
    });
    // 资金运用行业
    this.props
      .dispatch({
        type: 'qualificationManagementPlanMaintenanceM/getFundDictionList',
        // [资金运用行业]
        payload: {
          datakey: 'GJTJJHYFLI',
        },
      })
      .then(() => {
        this.getTableData();
      });
  }
  UNSAFE_componentWillReceiveProps(nextProps) {}
  // 获取表格数据
  getTableData = () => {
    const { searchObj, currentPage, numInPage, sortedInfo } = this.state;
    let obj = {};
    if (sortedInfo?.order) {
      (obj.columnKey = sortedInfo?.columnKey), (obj.order = sortedInfo?.order);
    }
    this.setState(
      {
        dataSource: undefined,
      },
      () => {
        this.props.dispatch({
          type: 'qualificationManagementPlanMaintenanceM/queryTable',
          payload: {
            ...searchObj,
            currentPage: currentPage,
            numInPage: numInPage,
            ...obj,
          },
          callback: (type, data) => {
            if (type == 'success') {
              this.setState({
                dataSource: data.dataSource,
                total: data.pageInfo && data.pageInfo.total,
              });
            }
          },
        });
      },
    );
  };
  //查询
  queryTableList = (e) => {
    if (Object.keys(e).length == 1 && Object.keys(e)[0] == 'codeId') {
      //产品名称精准查询时清空其他查询条件
      this.state.RANGEDATE.reset();
      this.state.RANGEDATEEnd.reset();
    }
    let tempQuery = {};
    for (let k in e) {
      if (k == 'startDateStart' || k == 'startDateEnd' || k == 'endDateStart' || k == 'endDateEnd') {
        tempQuery[k] = e[k].format('YYYY-MM-DD');
      } else {
        tempQuery[k] = e[k];
      }
    }
    this.setState(
      {
        searchObj: tempQuery,
        isReset: false,
        currentPage: 1,
        numInPage: 10,
      },
      () => {
        this.getTableData();
      },
    );
  };
  //表格页码排序改变调用
  handleTableChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    const { isReset } = this.state;
    this.setState(
      {
        sortedInfo: sorter,
      },
      () => {
        if (isReset) {
          //判断是否点击了重置 点击页码不进行后台查询
          message.warning('查询条件已被重置，请重新查询。');
          return;
        }
        this.setState(
          {
            currentPage: current,
            numInPage: pageSize,
          },
          () => {
            this.getTableData();
          },
        );
      },
    );
  };
  // 新增
  addClick = () => {
    this.setState({
      operatePageVisible: true,
      operateType: 1,
    });
  };
  // 展期
  deferDate = (record) => {
    this.setState({
      deferDateVisible: true,
      deferDateData: record,
    });
  };
  //详情
  detailItem = (record) => {
    this.setState({
      id: record.id,
      operatePageVisible: true,
      operateType: 3,
    });
  };
  //估值解析
  analysisItem = (record) => {
    sessionStorage.setItem(
      'GZJX_pageJump',
      JSON.stringify({
        dimension: '2',
        assetType: '01',
        code: record.tradingcode,
      }),
    );
    this.props.dispatch(routerRedux.push('/SystemManagement/valuationAnalysis'));

    // this.setState({
    //     id: record.id,
    //     operatePageVisible: true,
    //     operateType: 4,
    // })
  };
  // 编辑事件
  editItem = (record) => {
    this.setState({
      id: record.id,
      operatePageVisible: true,
      operateType: 2,
    });
  };
  // 删除事件
  deleteItem = (record) => {
    this.props.dispatch({
      type: 'qualificationManagementPlanMaintenanceM/deleteOne',
      payload: {
        id: record?.id,
      },
      callback: (type, data) => {
        if (type == 'success') {
          this.getTableData();
        }
      },
    });
  };
  // 新增编辑页返回主页
  onBack = (type) => {
    this.setState({
      id: '',
      operatePageVisible: false,
    });
    if (type == 'ok') {
      this.getTableData();
    }
  };
  // 展期模态框确定事件
  deferDateOk = () => {
    this.deferDateInfoRef.props.form.validateFields((err, fieldsValue) => {
      if (err) return;
      if (moment(fieldsValue.planEndDate).format('YYYY-MM-DD') == moment(this.state.deferDateData.planEndDate).format('YYYY-MM-DD')) {
        message.warning('还未重新选择终止日期，请重新选择!');
        return;
      }
      this.props.dispatch({
        type: 'qualificationManagementPlanMaintenanceM/deferDate',
        payload: {
          tradeId: this.state.deferDateData.id,
          exhibitionPeriod: fieldsValue.planEndDate?.format('YYYY-MM-DD'),
        },
        callback: (type) => {
          if (type == 'success') {
            this.getTableData();
          }
        },
      });
      this.setState({
        deferDateVisible: false,
      });
    });
  };
  // 展期模态框取消事件
  deferDateCancel = () => {
    this.setState({
      deferDateVisible: false,
    });
  };
  // 展期页面渲染
  deferDateInfo = () => {
    return (
      <>
        <FormGroup
          dataSource={[
            {
              dataIndex: 'planCreateDate',
              title: '资管计划成立日期',
              type: DATA_ENTRY.SINGLEDATE,
              initialValue: this.state.deferDateData?.planCreateDate ? moment(this.state.deferDateData?.planCreateDate) : undefined,
              disabled: true,
            },
            {
              dataIndex: 'planEndDate',
              title: '资管计划终止日期',
              disableBegin: this.state.deferDateData?.planEndDate ? moment(this.state.deferDateData?.planEndDate) : undefined,
              type: DATA_ENTRY.SINGLEDATE,
              initialValue: this.state.deferDateData?.planEndDate ? moment(this.state.deferDateData?.planEndDate) : undefined,
              rules: [{ required: true, message: '请选择资管计划终止日期!' }],
            },
          ]}
          autoLayout={false}
          rowNumber={2}
          onRef={(ref) => {
            this.deferDateInfoRef = ref;
          }}
        />
      </>
    );
  };
  render() {
    const { columns, dataSource, total, currentPage, numInPage, operatePageVisible, operateType, id, isReportPermissionBefore } = this.state;
    let { sortedInfo } = this.state;
    sortedInfo = sortedInfo || {};
    if (columns?.length && columns[columns?.length - 1].title != '操作') {
      columns.push({
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        width: 250,
        operates: [
          {
            title: '展期',
            onClick: (record, index) => {
              this.deferDate(record);
            },
            rules: {
              // 之前版本 -- 系统日期晚于或等于终止日期，才展示该按钮。(终止日期>系统日期，隐藏)
              //仅系统日期早于【投资计划终止日期】，才展示该按钮，【投资计划终止日期】无值时，也不提供展期功能
              hide: {
                relation: 'or',
                items: [
                  { key: 'planEndDate', value: [moment().format('YYYY-MM-DD')], relation: ['<'] },
                  { key: 'planEndDate', value: [null], relation: ['='] },
                ],
              },
            },
          },
          {
            title: '详情',
            onClick: (record, index) => {
              this.detailItem(record);
            },
          },
          {
            title: '估值解析',
            onClick: (record, index) => {
              this.analysisItem(record);
            },
            rules: {
              // 估值解析：资管计划属性不为“01 集合”时，可以点击估值解析
              disabled: { items: [{ key: 'planProperty', value: ['01'], relation: ['='] }] },
            },
          },
          {
            title: '编辑',
            onClick: (record, index) => {
              this.editItem(record);
            },
          },
          {
            title: '删除',
            onClick: (record, index) => {
              this.deleteItem(record);
            },
          },
        ],
      });
    }
    columns?.length &&
      columns.map((item) => {
        if (item.key == 'tradingcode' || item.key == 'planCreateDate' || item.key == 'planEndDate' || item.key == 'rateType') {
          item.sorter = true;
          item.sortOrder = sortedInfo.columnKey === item.key && sortedInfo.order;
        }
      });
    const searchProps = {
      dataSource: [
        {
          dataIndex: ['codeId', 'value'],
          title: '证券代码',
          type: DATA_ENTRY.SEARCHANDSELECTC,
          codeType: config.zcgljh,
        },
        {
          dataIndex: 'assetType',
          title: '资产类别',
          type: DATA_ENTRY.SELECT,
          allowClear: true,
          dataSource: this.props.qualificationManagementPlanMaintenanceM?.assetTypeList || [],
        },
        {
          dataIndex: 'manager',
          title: '管理人',
          type: DATA_ENTRY.INPUT,
          allowClear: true,
        },
        {
          dataIndex: ['startDateStart', 'startDateEnd'],
          title: '成立日区间',
          type: DATA_ENTRY.RANGEDATE,
          initialValue: [null, null],
          onRef: (ref) => this.setState({ RANGEDATE: ref }),
          disableFuture: false,
          allowClear: true,
        },
        {
          dataIndex: ['endDateStart', 'endDateEnd'],
          title: '到期日区间',
          type: DATA_ENTRY.RANGEDATE,
          initialValue: [null, null],
          onRef: (ref) => this.setState({ RANGEDATEEnd: ref }),
          disableFuture: false,
          allowClear: true,
        },
      ],
      //点击查询按钮
      onQuery: (e) => {
        this.queryTableList(e);
      },
      onClear: () => {
        //点击重置按钮
        this.setState({
          searchObj: {},
          sortedInfo: null, //排序对象
          isReset: true,
        });
      },
    };

    const newColumns =
      columns?.map((x) => {
        if (x.key == 'tradingcode') {
          return {
            ...x,
            fixed: 'left',
            width: '400px',
          };
        }

        if (x.key == 'assetType') {
          return {
            ...x,
            render: (t) => this.props.qualificationManagementPlanMaintenanceM?.assetTypeList?.filter((i) => i.value == t)[0]?.title || '--',
          };
        }
        //利率类型
        if (x.key == 'rateType') {
          return {
            ...x,
            render: (t) => this.props.qualificationManagementPlanMaintenanceM?.rateTypeList?.filter((i) => i.value == t)[0]?.title || '--',
          };
        }
        if (x.key == 'planCreateDate' || x.key == 'planEndDate') {
          return {
            ...x,
            width: '130px',
          };
        }
        return x;
      }) || undefined;
    return (
      <>
        {!operatePageVisible ? (
          <ContentPackage
            title='资产管理计划维护'
            contentHtml={
              <div>
                <div style={{ display: operatePageVisible ? 'none' : 'block' }}>
                  <div style={{ marginBottom: '10px' }}>
                    <AdvancedSearch {...searchProps} />
                  </div>
                  <div>
                    <PrimaryC title='新增' style={{ marginBottom: '10px' }} onClick={this.addClick} />
                  </div>
                  <TableC
                    columns={newColumns}
                    dataSource={dataSource}
                    current={currentPage}
                    total={total}
                    pageSize={numInPage}
                    selfScrollY={true}
                    rowKey='id'
                    onChange={this.handleTableChange}
                  />
                </div>

                <ModalC
                  title={'展期'}
                  visible={this.state.deferDateVisible}
                  maskClosable={false}
                  onOk={this.deferDateOk}
                  destroyOnClose={true}
                  confirmLoading={this.props.loading.effects['qualificationManagementPlanMaintenanceM/deferDate'] == true}
                  onCancel={this.deferDateCancel}
                  width={900}
                >
                  {this.deferDateInfo()}
                </ModalC>
              </div>
            }
          />
        ) : (
          <div style={{ height: '100%' }}>
            <UpdateModelC
              onBack={this.onBack}
              id={id}
              onRef={(ref) => {
                this.$operatePageC = ref;
              }}
              operateType={operateType}
              isReportPermissionBefore={isReportPermissionBefore}
            />
          </div>
        )}
      </>
    );
  }
}
